<template>
<div class="CreateTask" style="display:inline;">
    <Perm :level="[3]" :type="type" size="default" :label="label" @click.native="getTask(taskId)">
        <slot>{{label}}</slot><i :class="icon"></i>
    </Perm>
    <!-- :before-close="handleClose"  关闭提示功能 暂时取消 -->
    <el-dialog :append-to-body="true"  :title="label" :visible.sync="centerDialogVisible" width="50%" left top="5%">
        <el-form ref="form" :rules="rules" :model="form" label-width="100px" label-position="right">
            <el-form-item prop="planName" label="计划名称">
                <el-input v-model="form.planName"></el-input>
            </el-form-item>

            <el-form-item label="采集时间" required>
                <el-col :span="11">
                    <el-form-item prop="planStartTime">
                        <el-date-picker type="datetime" placeholder="采集任务开始时间" v-model="form.planStartTime" style="width: 100%"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="2" style="text-align: center">-</el-col>
                <el-col :span="11">
                    <el-form-item prop="planEndTime" required>
                        <el-date-picker type="datetime" placeholder="采集任务结束时间" v-model="form.planEndTime" style="width: 100%"></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-form-item>

            <el-form-item label="采集区域" required prop="townVillage">
                <el-col :span="16">
                    <div class="block">
                        <el-cascader type="primary" :options="options" :props="props" collapse-tags @change="changecollectTaskTown" v-model="form.townVillage"></el-cascader>
                        <el-button type="primary" style="margin-left: 10px" @click="selectAll">全选</el-button>
                        <el-button type="primary" style="margin-left: 10px" @click="selectNone">取消全选</el-button>
                    </div>
                </el-col>
            </el-form-item>

            <el-form-item label-width="0" required prop="planRequire">
                <div class="label">采集要求</div>
                <el-input type="textarea" class="textarea" placeholder="请输入采集要求" v-model="form.planRequire"></el-input>
            </el-form-item>

            <el-form-item label-width="0">
                <Upload label="通知/图片" @click="getUrlList"></Upload>
            </el-form-item>
        </el-form>

        <el-button @click="onSubmit('form')">保存计划任务</el-button>
    </el-dialog>
</div>
</template>

<script>
import {
    mapGetters
} from "vuex";
import {
    formatDate,
    convertKey,
    editDisplay 
} from "@/library";
import areaList from '@/areaList.js';
export default {
    props: {
        label: {
            type: String,
            default: "Button",
        },
        type: {
            type: String,
            default: "default",
        },
        icon: {
            type: String,
        },
        taskId:{
            type:Number,
            required:true
        }
    },

    data() {

        var VerifyplanStartTime = (rule, value, callback) => {
            if (!value) {
                callback(new Error("请选择采集开始的时间"));
            } else {
                callback();
            }
        };

        var VerifyplanEndTime = (rule, value, callback) => {
            if (value) {
                let planStartTime = +new Date(this.form.planStartTime);
                let planEndTime = +new Date(value);
                if (planEndTime - planStartTime <= 0) {
                    callback(new Error("结束时间不能小于开始时间"));
                } else {
                    this.form.planEndTime = value
                    callback();
                }
            } else {
                callback(new Error("请选择采集结束的时间"));
            }
        };

        var VerifyArea = (rule, value, callback) => {
            if (value instanceof Array && value.length > 0) {
                callback();
            } else {
                callback(new Error("您必须选择一个采集镇街"));
            }
        };

        return {
            areaList: areaList,
            importForm: {
                importFile: "",
            },
            centerDialogVisible: false,
            centerDialogVisible2: false,
            form: {},
            props: {
                multiple: true,
            },
            dialogImageUrl: "",
            dialogVisible: false,
            disabled: false,
            rules: {
                planName: [{
                    required: true,
                    message: "请输入活动名称",
                    trigger: "blur",
                }],
                planStartTime: [{
                    type: "date",
                    validator: VerifyplanStartTime,
                    required: true,
                    trigger: "change",
                }],

                planEndTime: [{
                    type: "date",
                    validator: VerifyplanEndTime,
                    required: true,
                    trigger: "change",
                }],

                townVillage: [{
                    type: "array",
                    validator: VerifyArea,
                    required: true,
                    trigger: "change",
                }],

                planRequire: [{
                    required: true,
                    message: "采集要求不能为空",
                    trigger: "blur",
                }]
            },
            villageMatch: [],
            townMatch: [],
            townVillage: {},
            townVillageCopy: {},
        };
    },
    mounted() {
        this.villageInit();
    },
    computed: {
        ...mapGetters({
            options: "getTreeData/filtersVillage",
        }),
    },
    methods: {
        // handleClose(done) {
        //   this.$confirm("确认关闭？")
        //     .then(() => {
        //       done();
        //     })
        //     .catch(() => {});
        // },
    getTask(id) {
        
        if(!id instanceof Number){
            this.$message.error("任务ID不存在，或当前任务已经被删除");
            return false
        }
        this.$axios
            .get("task/task/getAListOfPlans/", {
                params: {
                    "planInfo.id": this.taskId,
                },
            })
            .then((res) => {
                this.form = res.data.list[0];
                let treeData = this.form ?.treeData ?.treeItem[0] ?.children;
                let options;
                if (typeof treeData != "undefined") {
                    options = convertKey(treeData, {
                        administrativeName: "label",
                        administrativeCode: "value",
                    });
                    this.form.townVillage = options;
                } else {
                    this.form.townVillage = [];
                }
                // console.log(JSON.stringify(options,['label','value','children'])
                //构建 areas 回显数据
                this.area = editDisplay(this.form.treeData.list);

                delete this.form.treeData;
                this.dialogVisible = true;
                this.centerDialogVisible = true
            });
    },

        selectAll() {
            this.form.townVillage = this.areaList;
            this.changecollectTaskTown(this.form.townVillage);
        },
        selectNone() {
            this.form.townVillage = [];
            this.townVillage = {};
        },
        villageInit() {
            this.options.forEach((item) => {
                this.townMatch.push(item.value);
                this.villageMatch.push([
                    ...JSON.stringify([item.children]).match(/\d{12}/g),
                ]);
            });
        },
        changecollectTaskTown(e) {
            this.townVillage = {}
            let newSelect = new Map();
            // e.forEach((item) => {
            //     let town;
            //     let townIndex = this.townMatch ?.indexOf(item[0]);
            //     let villageIndex = this.villageMatch[townIndex] ?.indexOf(item[1]);

            //     town = JSON.parse(JSON.stringify(this.options[townIndex]));
            //     town.children = [
            //         JSON.parse(
            //             JSON.stringify(this.villageMatch[townIndex][villageIndex])
            //         ),
            //     ];

            //     if (newSelect.get(town.value)) {
            //         newSelect.get(town.value).children = [
            //             ...newSelect.get(town.value).children,
            //             ...town.children,
            //         ];
            //     } else {
            //         newSelect.set(town.value, town);
            //     }
            // });

            for (let index = 0; index < e.length; index++) {
                const item = e[index];

                let town;

                let townIndex = this.townMatch ?.indexOf(item[0]);
                let villageIndex = this.villageMatch[townIndex] ?.indexOf(item[1]);

                town = JSON.parse(JSON.stringify(this.options[townIndex]));

                if (typeof this.villageMatch[townIndex][villageIndex] === "undefined") {
                    console.log(
                        this.villageMatch[townIndex] + '>>>>>' + this.villageMatch[townIndex][villageIndex]
                    );
                    continue;
                } else {
                    town.children = [
                        JSON.parse(
                            JSON.stringify(this.villageMatch[townIndex][villageIndex])
                        ),
                    ];
                }
                if (newSelect.get(town.value)) {
                    newSelect.get(town.value).children = [
                        ...newSelect.get(town.value).children,
                        ...town.children,
                    ];
                } else {
                    newSelect.set(town.value, town);
                }
            }

            newSelect.forEach((item, index) => {
                this.townVillage[index] = item.children;
            });

            console.log(JSON.stringify(this.townVillage));
            // this.townVillage = newSelectTown;
        },

        // CascaderSuccess(res){
        //   console.log(res);
        //   this.form.area = res
        // },

        getUrlList(values) {
            if (!values) values = [];
            this.form.planFiles = values.join(',');
        },
        patternChange(date) {
            let oDate = new Date(date);
            return formatDate(+oDate);
        },
        createTask() {
            if (!localStorage.getItem("SYS_TYPE")) {
                this.$message.error("系统异常，请退出重新登录");
                this.$router.push(JSON.parse(localStorage.getItem('outLogin')))
                return false;
            }
      
            this.form.planType = localStorage.getItem("SYS_TYPE")
            this.form.area = JSON.stringify(this.townVillage);
            this.form.townVillage = JSON.stringify(this.townVillage);
            this.form.planStartTime = formatDate(this.form.planStartTime)
            this.form.planEndTime = formatDate(this.form.planEndTime)

            this.$axios
            .post("task/task/update", {
                params: {
                    id: this.form.id,
                    planName: this.form.planName,
                    planStatus: this.form.planStatus,
                    area: JSON.stringify(this.form.townVillage),
                    planRequire: this.form.planRequire,
                    planStartTime: this.form.planStartTime,
                    planEndTime: this.form.planEndTime,
                    planFiles: this.form.planFiles,
                    planType: this.form.planType,
                },
            })
            .then((res) => {
                if (res.errorCode === "00000") {
                    this.$message.success(res.errorMsg);
                    this.queryPlanAccordingToTheTask();
                    this.dialogVisible = false;
                } else {
                    this.$message.warning(res.errorMsg);
                }
            });

        },
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                // console.log(valid)
                if (valid) {
                    this.createTask();
                } else {
                    // console.log("error submit!!");
                    return false;
                }
            });
        },
    },
};
</script>

